package com.jdyfy.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jdyfy.entity.Announcement;
import com.jdyfy.entity.Project;
import com.jdyfy.entity.Publicity;
import com.jdyfy.mapper.ProjectMapper;
import com.jdyfy.mapper.PublicityMapper;
import com.jdyfy.service.PublicityService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class PublicityServiceImpl extends ServiceImpl<PublicityMapper, Publicity> implements PublicityService {

    @Autowired
    private PublicityMapper publicityMapper;

    @Autowired
    private ProjectMapper projectMapper;


    //根据项目编号集合获取每个项目对应的公告信息
    public List<Publicity> getPublicitysByProjectNumbers(List<String> projectNumbers) {
        return publicityMapper.getPublicitysByProjectNumbers(projectNumbers);
    }

    //根据公告名称删除公告
    @Override
    public boolean removeByName(String publicityName) {
        return publicityMapper.removeByName(publicityName);
    }

    @Scheduled(cron = "0 0 * * * ?") // "0 0 * * * ?" 每小时检查一次 /// "*/5 * * * * ?" 每五秒检查一次
    public void updateStatus() {
        log.info("定时任务执行中...");
        // 1. 更新公示状态
        publicityMapper.updateExpiredPublicity();

        // 2. 获取到期公示的所有项目
        List<String> expiredProjectNames = publicityMapper.getExpiredProjectNames();
        publicityMapper.updateProjectDealer();

        // 3. 更新项目表中的annoStatus字段为5
        if (expiredProjectNames != null && !expiredProjectNames.isEmpty()) {
            projectMapper.updateAnnoStatusByProjectNames(expiredProjectNames, 5);
            for(String expiredProjectName : expiredProjectNames) {
                publicityMapper.deleteByName(expiredProjectName);
            }
        }
    }
}
